<?php

defined('IN_CART') or die;

class CDb_mysql extends CDb{
	
	public function __construct($options = array()) {
		
		if(!extension_loaded("mysql")) {//如果未加载mysql扩展
			halt(L("NOT_SUPPORT_MYSQL"));
		}
		$host	= isset($options["host"]) ? $options["host"] : 'localhost';
		$port	= isset($options["port"]) ? $options["port"] : '3306';
		$user	= isset($options["user"]) ? $options["user"] : 'root';
		$pass	= isset($options["pass"]) ? $options["pass"] : '';
		$dbname = isset($options["dbname"]) ? $options["dbname"] : '';
	
		if(!$dbname) {
			halt(L("DBNAME_NOT_EXIST"));
		}

		if($port !='3306') $host .= ":".$port;

		$this->conn = @mysql_connect($host,$user,$pass);
		if(!$this->conn) {
			halt(L("CANNT_CONNECT_MYSQL"));
		}
		
		if(!mysql_select_db($dbname,$this->conn)) {
			halt(L("CANNT_SELECT_DB",$dbname));
		} 
		$this->dbversion = mysql_get_server_info($this->conn);
		mysql_query("SET NAMES utf8",$this->conn);
		if(version_compare($this->dbversion,"5.0.2",">=")) {
			mysql_query("SET SESSION SQL_MODE=''",$this->conn);
		}
	}

	public function quoteKey($key) {
		$key = trim($key);
		if(!preg_match('/[,\'\"\*\(\)`.\s]/',$key)) {
			return '`' . $key . '`';
		}
		return $key;
	}

	public function quoteValue($value) {
		if(is_string($value)) {
			$value = '\'' . $this->escape($value) . '\'';
		} else if(is_array($value)) {
			$value = array_map(array($this,"quoteValue"),$value);
		} else if(is_bool($value)) {
			$value = $value ? '1' : '0';	
		} else if(is_null($value)) {
			$value = 'null';
		}
		return $value;
	}
	
	//array(array("id"=>1,"v"=>2),array("id"=>3,"v"=>2))
	public function insertMulti($dataList,$options = array(),$replace = false) {
		if(!$dataList || !is_array($dataList) || !is_array(current($dataList))) return false;

		$fields = array_map(array($this,"quoteKey"),array_keys(current($dataList)));
		$values = array();
		foreach($dataList as $data) {
			$value = array();
			foreach($data as $key => $val) {
				$val		= $this->quoteValue($val);//如果出现非标量数据，直接替换成'',
				$value[]	= is_scalar($val) ? $val : '';
			}
			$values[] = cimplode($value);
		}
		$sql = ($replace ? 'REPLACE INTO' : 'INSERT INTO ')
			 . $this->quoteKey($options['table'])
			 . cimplode($fields)
			 . ' VALUES '
			 . implode(",",$values)
			 ;
		return $this->execute($sql) ? $this->getAffectedRows() : false;
	}

	public function execute($sql) {
		if(!$sql || !$this->conn) return false;
		
		$this->sql	    = $sql;
		$this->query	= mysql_query($sql,$this->conn);
		if(false === $this->query) {
			$this->error();
			return false;
		}
		return true;
	}
	
	public function getLastId() {
		return mysql_insert_id($this->conn);
	}

	public function getAffectedRows() {
		return mysql_affected_rows($this->conn);
	}

	public function getResults($type = 'rows',$keyid = '') {
		$results = array();
		if($this->query) {
			if('rows' == $type || 'col' == $type) {
				while($row = mysql_fetch_assoc($this->query)) {
					if(!$keyid) {
						$results[]			   = 'rows' == $type ? $row : current($row);
					} else {
						$results[$row[$keyid]] = $row;
					}
				}
			} else if('row' == $type || 'val' == $type) {
				$results = mysql_fetch_assoc($this->query);
				if('val' == $type) $results = current($results);
			}
			$this->free();//取完结果，立即释放
		}
		return $results;
	}
	
	public function error() {
		$this->error = mysql_error($this->conn)
					 . '\n [SQL：] '
					 . $this->sql;
		return $this->error;
	}

	public function errno() {
		$this->errno = mysql_errno($this->conn);
		return $this->errno;
	}
	

	public function escape($string) {
		if($this->conn) {
			return mysql_real_escape_string($string,$this->conn);
		} else {
			return mysql_escape_string($string);
		}
	}

	public function free() {
		if($this->query) {
			mysql_free_result($this->query);
			$this->query = null;
		}
	}
}


